<template>
  <v-app>
    <v-container class="pa-4" fluid>
      <!-- 顶部工具栏 -->
      <v-row class="mb-4">
        <v-col cols="12">
          <v-card>
            <v-card-title class="d-flex align-center">
              <v-icon class="mr-2">mdi-format-list-checks</v-icon>
              异步任务管理
              <v-spacer></v-spacer>
              <v-chip class="mr-2" color="primary" variant="outlined">
                总计: {{ taskCount }}
              </v-chip>
              <v-btn color="primary" prepend-icon="mdi-plus" @click="openCreateDialog">
                创建任务
              </v-btn>
            </v-card-title>
          </v-card>
        </v-col>
      </v-row>

      <!-- 状态筛选标签 -->
      <v-row class="mb-4">
        <v-col cols="12">
          <v-chip-group v-model="selectedStatus" mandatory>
            <v-chip filter value="all">全部 ({{ taskCount }})</v-chip>
            <v-chip color="grey" filter :value="TaskStatus.PENDING"
              >待处理 ({{ pendingCount }})</v-chip
            >
            <v-chip color="blue" filter :value="TaskStatus.IN_PROGRESS"
              >进行中 ({{ inProgressCount }})</v-chip
            >
            <v-chip color="green" filter :value="TaskStatus.COMPLETED"
              >已完成 ({{ completedCount }})</v-chip
            >
            <v-chip color="red" filter :value="TaskStatus.FAILED">失败 ({{ failedCount }})</v-chip>
          </v-chip-group>
        </v-col>
      </v-row>

      <!-- 任务列表 -->
      <v-row>
        <v-col cols="12">
          <v-card v-if="loading" class="pa-4">
            <v-progress-linear color="primary" indeterminate></v-progress-linear>
            <div class="text-center mt-2">加载中...</div>
          </v-card>

          <v-card v-else-if="error" class="pa-4" color="error" variant="tonal">
            <v-card-text>
              <v-icon class="mr-2">mdi-alert-circle</v-icon>
              {{ error }}
            </v-card-text>
          </v-card>

          <v-card v-else-if="!filteredTasks || filteredTasks.length === 0" class="pa-4">
            <v-card-text class="text-center">
              <v-icon color="grey" size="64">mdi-inbox</v-icon>
              <div class="text-h6 mt-2">暂无任务</div>
            </v-card-text>
          </v-card>

          <v-list v-else lines="three">
            <v-list-item v-for="task in filteredTasks" :key="task.id" border class="mb-2" rounded>
              <template #prepend>
                <v-avatar :color="getStatusColor(task.status)" size="48">
                  <v-icon>{{ getStatusIcon(task.status) }}</v-icon>
                </v-avatar>
              </template>

              <v-list-item-title class="text-h6">
                {{ getTaskTypeLabel(task.task_type) }}
              </v-list-item-title>

              <v-list-item-subtitle>
                <div class="mt-1">
                  <v-chip class="mr-2" :color="getStatusColor(task.status)" size="small">
                    {{ getStatusLabel(task.status) }}
                  </v-chip>
                  <v-chip class="mr-2" size="small" variant="outlined"> ID: {{ task.id }} </v-chip>
                  <span class="text-caption"> 创建时间: {{ formatTime(task.created_at) }} </span>
                </div>

                <!-- 进度条 -->
                <v-progress-linear
                  v-if="task.status === TaskStatus.IN_PROGRESS"
                  class="mt-2"
                  color="blue"
                  height="6"
                  :model-value="task.progress || 0"
                ></v-progress-linear>

                <!-- 错误信息 -->
                <div v-if="task.error_message" class="mt-2 text-error">
                  <v-icon size="small">mdi-alert</v-icon>
                  {{ task.error_message }}
                </div>
              </v-list-item-subtitle>

              <template #append>
                <div class="d-flex flex-column ga-1">
                  <v-btn
                    v-if="task.status === TaskStatus.PENDING && task.id"
                    color="blue"
                    size="small"
                    variant="tonal"
                    @click="startTask(task.id)"
                  >
                    开始
                  </v-btn>
                  <v-btn
                    v-if="task.status === TaskStatus.IN_PROGRESS && task.id"
                    color="green"
                    size="small"
                    variant="tonal"
                    @click="completeTask(task.id)"
                  >
                    完成
                  </v-btn>
                  <v-btn
                    v-if="task.status === TaskStatus.IN_PROGRESS && task.id"
                    color="red"
                    size="small"
                    variant="tonal"
                    @click="failTask(task.id)"
                  >
                    失败
                  </v-btn>
                  <v-btn
                    v-if="task.id"
                    color="grey"
                    icon="mdi-delete"
                    size="small"
                    variant="text"
                    @click="deleteTask(task.id)"
                  ></v-btn>
                </div>
              </template>
            </v-list-item>
          </v-list>
        </v-col>
      </v-row>

      <!-- 底部操作栏 -->
      <v-row class="mt-4">
        <v-col cols="12">
          <v-card>
            <v-card-actions>
              <v-btn color="warning" prepend-icon="mdi-broom" @click="cleanupCompleted">
                清理已完成任务
              </v-btn>
              <v-btn color="error" prepend-icon="mdi-delete-sweep" @click="cleanupFailed">
                清理失败任务
              </v-btn>
              <v-spacer></v-spacer>
              <v-btn color="grey" prepend-icon="mdi-refresh" @click="refreshTasks"> 刷新 </v-btn>
            </v-card-actions>
          </v-card>
        </v-col>
      </v-row>
    </v-container>

    <!-- 创建任务对话框 -->
    <v-dialog v-model="createDialog" max-width="600">
      <v-card>
        <v-card-title>创建新任务</v-card-title>
        <v-card-text>
          <v-select
            v-model="newTask.task_type"
            class="mb-4"
            :items="taskTypes"
            label="任务类型"
            variant="outlined"
          ></v-select>
          <v-textarea
            v-model="newTaskData"
            label="业务数据 (JSON)"
            placeholder='{"key": "value"}'
            rows="5"
            variant="outlined"
          ></v-textarea>
        </v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn @click="createDialog = false">取消</v-btn>
          <v-btn color="primary" @click="createTask">创建</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-app>
</template>

<script lang="ts" setup>
import { useSystemStateListener } from '@/composables/useSystemStateListener'
import { TaskStatus, TaskType } from '~types/async-task'
import type { AsyncTask } from '~types/async-task'

// 启动系统状态监听器
useSystemStateListener()

// 状态
const selectedStatus = ref<TaskStatus | 'all'>('all')
const loading = ref(false)
const error = ref<string | null>(null)
const tasks = ref<AsyncTask[]>([])
const taskCount = ref(0)
const pendingCount = ref(0)
const inProgressCount = ref(0)
const completedCount = ref(0)
const failedCount = ref(0)

// 创建任务对话框
const createDialog = ref(false)
const newTask = ref({
  task_type: TaskType.DATA_EXPORT
})
const newTaskData = ref('{}')

// 任务类型选项
const taskTypes = [
  { title: '数据导出', value: TaskType.DATA_EXPORT },
  { title: '批量处理', value: TaskType.BATCH_PROCESSING },
  { title: '同步操作', value: TaskType.SYNC_OPERATION },
  { title: '其他', value: TaskType.OTHER }
]

// 计算属性：过滤后的任务列表
const filteredTasks = computed(() => {
  if (selectedStatus.value === 'all') {
    return tasks.value
  }
  return tasks.value.filter(task => task.status === selectedStatus.value)
})

// 获取任务列表
async function loadTasks() {
  loading.value = true
  error.value = null

  try {
    const result = await _pre_.asyncTask.queryTasks({
      limit: 100,
      sortBy: 'created_at',
      sortOrder: 'desc'
    })

    if (result.success && result.data) {
      tasks.value = result.data
    } else {
      throw new Error(result.error || '加载任务失败')
    }
  } catch (error_) {
    error.value = error_ instanceof Error ? error_.message : '未知错误'
    console.error('加载任务失败:', error_)
  } finally {
    loading.value = false
  }
}

// 加载统计数据
async function loadStats() {
  try {
    const [countRes, pendingRes, inProgressRes, completedRes, failedRes] = await Promise.all([
      _pre_.asyncTask.getTaskCount(),
      _pre_.asyncTask.getPendingTasks(),
      _pre_.asyncTask.getInProgressTasks(),
      _pre_.asyncTask.getCompletedTasks(),
      _pre_.asyncTask.getFailedTasks()
    ])

    if (countRes.success && countRes.data !== undefined) {
      taskCount.value = countRes.data
    }
    if (pendingRes.success && pendingRes.data) {
      pendingCount.value = pendingRes.data.length
    }
    if (inProgressRes.success && inProgressRes.data) {
      inProgressCount.value = inProgressRes.data.length
    }
    if (completedRes.success && completedRes.data) {
      completedCount.value = completedRes.data.length
    }
    if (failedRes.success && failedRes.data) {
      failedCount.value = failedRes.data.length
    }
  } catch (error_) {
    console.error('加载统计数据失败:', error_)
  }
}

// 刷新任务
async function refreshTasks() {
  await Promise.all([loadTasks(), loadStats()])
}

// 打开创建对话框
function openCreateDialog() {
  createDialog.value = true
  newTask.value = { task_type: TaskType.DATA_EXPORT }
  newTaskData.value = '{}'
}

// 创建任务
async function createTask() {
  try {
    let businessData: Record<string, any> = {}
    try {
      businessData = JSON.parse(newTaskData.value)
    } catch {
      alert('业务数据格式错误，请输入有效的JSON')
      return
    }

    const result = await _pre_.asyncTask.createTask({
      task_type: newTask.value.task_type,
      business_data: businessData
    })

    if (result.success) {
      createDialog.value = false
      await refreshTasks()
    } else {
      alert(result.error || '创建任务失败')
    }
  } catch (error_) {
    console.error('创建任务失败:', error_)
    alert('创建任务失败')
  }
}

// 开始任务
async function startTask(id: number) {
  try {
    const result = await _pre_.asyncTask.markAsInProgress(id)
    if (result.success) {
      await refreshTasks()
    } else {
      alert(result.error || '开始任务失败')
    }
  } catch (error_) {
    console.error('开始任务失败:', error_)
  }
}

// 完成任务
async function completeTask(id: number) {
  try {
    const result = await _pre_.asyncTask.markAsCompleted(id, { completed: true })
    if (result.success) {
      await refreshTasks()
    } else {
      alert(result.error || '完成任务失败')
    }
  } catch (error_) {
    console.error('完成任务失败:', error_)
  }
}

// 标记任务失败
async function failTask(id: number) {
  const errorMsg = prompt('请输入失败原因:')
  if (!errorMsg) return

  try {
    const result = await _pre_.asyncTask.markAsFailed(id, errorMsg)
    if (result.success) {
      await refreshTasks()
    } else {
      alert(result.error || '标记失败任务失败')
    }
  } catch (error_) {
    console.error('标记失败任务失败:', error_)
  }
}

// 删除任务
async function deleteTask(id: number) {
  if (!confirm('确定要删除这个任务吗？')) return

  try {
    const result = await _pre_.asyncTask.deleteTask(id)
    if (result.success) {
      await refreshTasks()
    } else {
      alert(result.error || '删除任务失败')
    }
  } catch (error_) {
    console.error('删除任务失败:', error_)
  }
}

// 清理已完成任务
async function cleanupCompleted() {
  if (!confirm('确定要清理30天前的已完成任务吗？')) return

  try {
    const result = await _pre_.asyncTask.cleanupCompletedTasks(30)
    if (result.success) {
      await refreshTasks()
    } else {
      alert(result.error || '清理已完成任务失败')
    }
  } catch (error_) {
    console.error('清理已完成任务失败:', error_)
  }
}

// 清理失败任务
async function cleanupFailed() {
  if (!confirm('确定要清理7天前的失败任务吗？')) return

  try {
    const result = await _pre_.asyncTask.cleanupFailedTasks(7)
    if (result.success) {
      await refreshTasks()
    } else {
      alert(result.error || '清理失败任务失败')
    }
  } catch (error_) {
    console.error('清理失败任务失败:', error_)
  }
}

// 工具函数
function getStatusColor(status: TaskStatus): string {
  const colors: Record<TaskStatus, string> = {
    [TaskStatus.PENDING]: 'grey',
    [TaskStatus.IN_PROGRESS]: 'blue',
    [TaskStatus.COMPLETED]: 'green',
    [TaskStatus.FAILED]: 'red'
  }
  return colors[status] || 'grey'
}

function getStatusIcon(status: TaskStatus): string {
  const icons: Record<TaskStatus, string> = {
    [TaskStatus.PENDING]: 'mdi-clock-outline',
    [TaskStatus.IN_PROGRESS]: 'mdi-loading',
    [TaskStatus.COMPLETED]: 'mdi-check-circle',
    [TaskStatus.FAILED]: 'mdi-alert-circle'
  }
  return icons[status] || 'mdi-help-circle'
}

function getStatusLabel(status: TaskStatus): string {
  const labels: Record<TaskStatus, string> = {
    [TaskStatus.PENDING]: '待处理',
    [TaskStatus.IN_PROGRESS]: '进行中',
    [TaskStatus.COMPLETED]: '已完成',
    [TaskStatus.FAILED]: '失败'
  }
  return labels[status] || status
}

function getTaskTypeLabel(type: string): string {
  const labels: Record<string, string> = {
    [TaskType.DATA_EXPORT]: '数据导出',
    [TaskType.BATCH_PROCESSING]: '批量处理',
    [TaskType.SYNC_OPERATION]: '同步操作',
    [TaskType.OTHER]: '其他'
  }
  return labels[type] || type
}

function formatTime(timestamp: number): string {
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 初始化加载
onMounted(() => {
  refreshTasks()
})
</script>
